<template>
  <div :class="className" :style="{height:height,width:width}"/>
</template>

<script>
  import * as echarts from 'echarts'
  import resize from './mixins/resize'

  require('echarts/theme/macarons') // echarts theme

  const animationDuration = 6000

  export default {
    mixins: [resize],
    props: {
      className: {
        type: String,
        default: 'chart'
      },
      width: {
        type: String,
        default: '100%'
      },
      height: {
        type: String,
        default: '300px'
      }
    },
    data() {
      return {
        url: "ws://127.0.0.1:8080/websocket/ry",
        ws: null,
        chart: null,
        xxList: [], // 存储后端推送的数据
        chartOption: {
          tooltip: {
            trigger: 'axis',
            axisPointer: {type: 'shadow'}
          },
          grid: {
            top: 10,
            left: '2%',
            right: '2%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
            axisTick: {alignWithLabel: true}
          },
          yAxis: {
            type: 'value',
            axisTick: {show: false}
          },
          series: [{
            name: '数据展示',
            type: 'bar',
            barWidth: '60%',
            data: [], // 初始为空，将通过websocket填充
            animationDuration: 2000
          }]
        },
        animationDuration: 2000 // 动画时长
      }
    },
    mounted() {
      this.initChart();
      this.initWebSocket();
    },
    methods: {
      initChart() {
        this.chart = echarts.init(this.$el, 'macarons')
        this.chart.setOption(this.chartOption);
      },
      initWebSocket() {
        // 连接 WebSocket（根据实际后端地址调整）
        const wsuri = this.url;
        this.ws = new WebSocket(wsuri);
        const self = this;
        /*    this.ws.onopen = function (event) {
              self.text_content = self.text_content + "已经打开连接!" + "\n";
            };*/
        // 监听消息
        this.ws.onmessage = (event) => {
          try {
            this.xxList = JSON.parse(event.data).yData; // 赋值到 Vue 的 data
            console.log('Received data:', this.xxList.yData); // 调试
            // 关键修改：处理yData数组

            // 动态更新series数据
            this.chart.setOption({
              series: [{
                data: this.xxList // 直接绑定数组
              }]
            });
            console.log('图表数据已更新:', this.xxList);
            // 动态更新图表数据
          } catch (e) {
            console.error('WebSocket 数据解析错误:', e);
          }
        };
        // 错误处理
        this.ws.onerror = (error) => {
          console.error('WebSocket 错误:', error);
        };
        this.ws.onclose = function (event) {
          self.text_content = self.text_content + "已经关闭连接!" + "\n";
        };

      },


      renderChart() {
        this.chart.setOption({
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          grid: {
            top: 10,
            left: '2%',
            right: '2%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: [{
            type: 'category',
            data: this.chartData.categories,
            axisTick: {
              alignWithLabel: true
            }
          }],
          yAxis: [{
            type: 'value',
            axisTick: {
              show: false
            }
          }],
          series: this.chartData.series.map(item => ({
            name: item.name,
            type: 'bar',
            stack: 'vistors',
            barWidth: '60%',
            data: item.data,
            animationDuration: this.animationDuration
          }))
        });
      },
      beforeDestroy() {
        // 组件销毁时关闭 WebSocket
        if (this.ws) {
          this.ws.close();
        }
        if (!this.chart) {
          return
        }
        this.chart.dispose()
        this.chart = null
      },
    }
  }
</script>
